package com.hnluchuan.staff.web.controller.admin;

import java.io.*;
import java.math.BigInteger;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.hnluchuan.staff.common.UserType;
import com.hnluchuan.staff.dao.EducationDAO;
import com.hnluchuan.staff.dao.EmployeeDAO;
import com.hnluchuan.staff.dto.*;
import com.hnluchuan.staff.model.Education;
import com.hnluchuan.staff.model.EmergencyContact;
import com.hnluchuan.staff.model.Employee;
import com.hnluchuan.staff.model.User;
import com.hnluchuan.staff.service.*;
import com.hnluchuan.utils.exception.BizException;
import com.sun.tools.internal.ws.processor.model.Model;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hnluchuan.core.support.Page;
import com.hnluchuan.staff.web.controller.BaseController;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;

@Controller
@RequestMapping(value = "/admin/employee", produces="text/html;charset=UTF-8")
public class AdminEmployeeController extends BaseController {

	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private EducationService educationService;
	@Autowired
	private EmergencyContactService emergencyContactService;
	@Autowired
	private FamilyService familyService;
	@Autowired
	private ExperienceService experienceService;
	@Autowired
	private UserService userService;
	@Autowired
	private  EmployeeFileService employeeFileService;
	@Autowired
	private  DepartmentService departmentService;
	@RequestMapping(value = "/detail")
	public String detail(Map<String, Object> map, Long id) throws Exception {

		UserDTO UserDTO = getCurrentUserDTO();
		map.put("type", UserDTO.getType());
		if (id != null) {
			EmployeeDTO dto = employeeService.load(id);
			//部门
			DepartmentDTO departmentDTO=new DepartmentDTO();
			departmentDTO.setId(dto.getDepartment().getId());
			departmentDTO	=departmentService.findOne(departmentDTO);
			dto.setDepartment(departmentDTO);
			//学历
			EducationDTO education = new EducationDTO();
			education.setEmployee(dto);
			List<EducationDTO> edlist = educationService.findAll(education);
			//紧急联系人
			EmergencyContactDTO emergencyContact = new EmergencyContactDTO();
			emergencyContact.setEmployee(dto);
			List<EmergencyContactDTO> emlist = emergencyContactService.findAll(emergencyContact);
			//家庭
			FamilyDTO familyDTO = new FamilyDTO();
			familyDTO.setEmployee(dto);
			List<FamilyDTO> falist = familyService.findAll(familyDTO);
			//工作
			ExperienceDTO experienceDTO = new ExperienceDTO();
			experienceDTO.setEmployee(dto);
			List<ExperienceDTO> exlist = experienceService.findAll(experienceDTO);
			//附件，图片
			EmployeeFileDTO employeeFileDTO=new EmployeeFileDTO();
			employeeFileDTO.setEmployee(dto);
			List<EmployeeFileDTO> filist=employeeFileService.findAll(employeeFileDTO);
			//部门信息
			List<DepartmentDTO> delist=departmentService.findAll();
			map.put("delist", delist);
			map.put("filist", filist);
			map.put("edlist", edlist);
			map.put("emlist", emlist);
			map.put("falist", falist);
			map.put("exlist", exlist);
			map.put("n", dto);
			return "admin/employee/employee_detail";
		} else {
			if (UserDTO.getType() != 1) {
				EmployeeDTO e = new EmployeeDTO();
				e.setUser(UserDTO);
				List<EmployeeDTO> list = employeeService.findAll(e);
				if (list.size() == 1) {
					map.put("info", "你已经添加过信息！！");
					return "/admin/employee/error";
				} else if (list.size() < 1) {
					return "/admin/employee/employee_add_all";
				}
			} else if (UserDTO.getType() == 1) {
				List<DepartmentDTO> delist=departmentService.findAll();
				map.put("delist", delist);
				return "/admin/employee/employee_admin_add";
			}
		}

		return "admin/employee/employee_detail";
	}

	@ResponseBody
	@RequestMapping(value = "/save")
	public String save(EmployeeDTO dto, ConflictField conflictField,
					   EducationsDTO educationsDTOS, FamilysDTO familyDTOS, EmergencyContactsDTO emergencyContactDTOS, ExperiencesDTO experienceDTOS, HttpServletRequest request
	) throws Exception {
		UserDTO UserDTO = getCurrentUserDTO();
		dto.setUser(UserDTO);
		List<EducationDTO> edlist = new ArrayList<EducationDTO>();
		edlist = educationsDTOS.getEducationsDTOS();
		List<ExperienceDTO> exlist = new ArrayList<ExperienceDTO>();
		exlist = experienceDTOS.getExperienceDTOS();
		List<FamilyDTO> falist = new ArrayList<FamilyDTO>();
		falist = familyDTOS.getFamilyDTOS();
		List<EmergencyContactDTO> emlist = new ArrayList<EmergencyContactDTO>();
		emlist = emergencyContactDTOS.getEmergencyContactDTOS();
//		if (dto.getId() == null) {
//
//			if (UserDTO.getType() == 1) {
//				UserDTO userDTO = new UserDTO();
//				userDTO.setUsername(dto.getIDCard());
//				if (userService.findOne(userDTO) == null) {
//					String newPwd = passwordEncoder.encodePassword("123456", userDTO.getUsername());
//					userDTO.setPassword(newPwd);
//					userDTO.setDeleted(false);
//					userDTO.setType(UserType.Normal.getValue());
//					Long id = userService.create(userDTO);
//					UserDTO.setId(id);
//					dto.setUser(UserDTO);
//				} else {
//					throw new BizException("此用户已存在");
//				}
//			} else {
//				dto.setStatus(1);
//			}
//			Long id = employeeService.create(dto);
//			dto.setId(id);
//			file(request, filedescribe1, file1, filedescribe2, file2, filedescribe3, file3, UserDTO);
//			//学历添加
//			for (EducationDTO e : edlist
//					) {
//				if (e.getMajor() == null && e.getMajor().equals("")) {
//					e.setEmployee(dto);
//					educationService.create(e);
//				}
//			}
//			//工作经验添加
//
//
//			for (ExperienceDTO e : exlist
//					) {
//				if (e.getPosition() != null && !e.getPosition().equals("")) {
//					e.setEmployee(dto);
//					experienceService.create(e);
//				}
//
//			}
//			//家庭添加
//
//			for (FamilyDTO e : falist
//					) {
//				if (e.getName() != null && !e.getName().equals("")) {
//					e.setEmployee(dto);
//					familyService.create(e);
//				}
//			}
//
//
//			//紧急联系添加
//
//
//			for (EmergencyContactDTO e : emlist
//					) {
//				if (e.getName() != null && !e.getName().equals("")) {
//					e.setEmployee(dto);
//					emergencyContactService.create(e);
//				}
//			}
//                     if(UserDTO.getType()==1)
//					 {
//					 	return ok();
//					 }else
//					 {
//					 	Map<String ,Object> map=new HashMap<>();
//					 	info(map,
//						request);
//					 }
//
//		} else
		if (UserDTO.getType() == 1) {
//			throw new RuntimeException("请实现更新逻辑，并删除该行");


				EmployeeDTO employeeDTO= new EmployeeDTO();
			   employeeDTO.setId(dto.getId());
			   employeeDTO = employeeService.findOne(employeeDTO);
				UserDTO userDTO = new UserDTO();
				userDTO.setId(employeeDTO.getUser().getId());
			    userDTO = userService.findOne(userDTO);
				if(dto.getStatus()==1&&userDTO==null)
				{
					throw  new BizException("此员工已经离职，不能修改信息！！");
				}else if(dto.getStatus()==2)
				{
					userDTO.setId(employeeDTO.getUser().getId());
					userDTO = userService.findOne(userDTO);
					userDTO.setDeleted(true);
					userService.updateAllFields(userDTO);
				}else if(dto.getStatus()==3&&userDTO==null)
				{
					throw  new BizException("离职用户不能修改信息！！");
				}
				userDTO = userService.findOne(userDTO);
				dto.setUser(userDTO);
				EmployeeDTO old = employeeService.load(dto.getId());
			EmployeeDTO e1=new EmployeeDTO();
			e1.setId(dto.getId());
			e1=employeeService.findOne(e1);
//			 确定哪些字段是在详情页面需要修改的，不在详情页修改的，就不需要在这里set值。updated和updatedBy不需要在这里处理，框架会统一处理
			old.setDepartment(dto.getDepartment());
			old.setId(dto.getId());
			old.setUser(e1.getUser());
			old.setPosition(dto.getPosition());
			old.setName(dto.getName());
			old.setBirth(dto.getBirth());
			old.setSex(dto.getSex());
			old.setHeight(dto.getHeight());
			old.setWeight(dto.getWeight());
			old.setPlace(dto.getPlace());
			old.setNation(dto.getNation());
			old.setPhone(dto.getPhone());
			old.setIDCard(dto.getIDCard());
			old.setSchool(dto.getSchool());
			old.setMajor(dto.getMajor());
			old.setEducation(dto.getEducation());
			old.setLocation(dto.getLocation());
			old.setAddress(dto.getAddress());
			old.setWechat(dto.getWechat());
			old.setEmail(dto.getEmail());
			old.setMarry(dto.getMarry());
			old.setInTime(dto.getInTime());
			old.setStatus(dto.getStatus());
			employeeService.updateAllFields(old);
			//学历更新

			if (edlist != null) {
				for (EducationDTO e : edlist
						) {
					educationService.updateAllFields(e);
				}
			}

			//工作经验更新

			if (exlist != null) {
				for (ExperienceDTO e : exlist
						) {
					experienceService.updateAllFields(e);
				}
			}

			//家庭更新

			if (falist != null) {
				for (FamilyDTO e : falist
						) {
					familyService.updateAllFields(e);
				}
			}

			//紧急联系人跟新

			if (emlist != null) {
				for (EmergencyContactDTO e : emlist
						) {
					emergencyContactService.updateAllFields(e);
				}
			}

		} else {
			throw new RuntimeException("管理员才可以修改！！！");
		}
		return ok();
	}


	@ResponseBody
	@RequestMapping(value = "/ret")
	public String ret(Long idr) throws Exception {
		System.out.printf(idr.toString());
		if (idr == -1) {

			return ok();
		}
		return ok();
	}


	@ResponseBody
	@RequestMapping(value = "/delete")
	public String delete(Long[] ids) throws IOException {
		System.out.printf("delete==============================================");
		UserDTO UserDTO = getCurrentUserDTO();
		if (UserDTO.getId() != 1) {
			throw new BizException("没有权限");
		} else {

			for (int i = 0; i < ids.length; i++) {
				Long id;
				EmployeeDTO employee = new EmployeeDTO();
				employee.setId(ids[i]);
				//学历删除
				EducationDTO education = new EducationDTO();
				education.setEmployee(employee);
				List<EducationDTO> l1 = educationService.findAll(education);
				if (l1.size() > 0) {
					for (EducationDTO e : l1
							) {
						educationService.deleteById(e.getId());
					}
				}
				//紧急联系人删除
				EmergencyContactDTO emergencyContactDTO = new EmergencyContactDTO();
				emergencyContactDTO.setEmployee(employee);
				List<EmergencyContactDTO> l2 = emergencyContactService.findAll(emergencyContactDTO);
				if (l2.size() > 0) {
					for (EmergencyContactDTO e : l2
							) {
						emergencyContactService.deleteById(e.getId());
					}
				}
				//家庭删除
				FamilyDTO familyDTO = new FamilyDTO();
				familyDTO.setEmployee(employee);
				List<FamilyDTO> l3 = familyService.findAll(familyDTO);
				if (l3.size() > 0) {
					for (FamilyDTO e :
							l3) {
						familyService.deleteById(e.getId());
					}
				}

				//工作经验
				ExperienceDTO experienceDTO = new ExperienceDTO();
				experienceDTO.setEmployee(employee);
				List<ExperienceDTO> l4 = experienceService.findAll(experienceDTO);
				if (l4.size() > 0) {
					for (ExperienceDTO e : l4
							) {
						experienceService.deleteById(e.getId());
					}
				}

			}
			employeeService.deleteByIds(ids);
		}
		return ok();
	}

	@RequestMapping(value = "/list")
	public String list(EmployeeDTO dto, Boolean search, Map<String, Object> map, Page page) {
		UserDTO userDTO = getCurrentUserDTO();
		List<EmployeeDTO> dtos;
		if (userDTO.getType() != 1) {
			dto.setUser(userDTO);
			dtos = employeeService.findAll(dto);


		} else {
			dtos = employeeService.find(dto, page);
			for (int i=0;i<dtos.size();i++
					) {
				EmployeeDTO e=dtos.get(i);
				DepartmentDTO department=new DepartmentDTO();
				department.setId(e.getDepartment().getId());
				department=departmentService.findOne(department);
				e.setDepartment(department);
				dtos.set(i,e); }

		}

//		long id=getCurrentUserDTO().getId();
//		map.put("id",id);
		map.put("list", dtos);
		map.put("query", dto);
		map.put("search", search);
		return "admin/employee/employee_list";
	}

	@RequestMapping(value = "/search")
	public String search(EmployeeDTO dto, Map<String, Object> map, Page page) {
		List<EmployeeDTO> dtos = employeeService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		return "admin/employee/employee_search";
	}

	@RequestMapping(value = "/getUserId")
	public String getUserId(UserDTO dto) {
		System.out.printf(dto.getId().toString());

		return ok();
	}
	//员工个人信息添加
	@ResponseBody
	@RequestMapping(value = "/infoadd")
	public String infoadd (EmployeeDTO dto,
						   EducationsDTO educationsDTOS, FamilysDTO familyDTOS, EmergencyContactsDTO emergencyContactDTOS, ExperiencesDTO experienceDTOS, HttpServletRequest request,
						   EmployeeFileDTOS employeeFileDTOS ) throws Exception {
		UserDTO UserDTO = getCurrentUserDTO();
		dto.setUser(UserDTO);
		List<EducationDTO> edlist = new ArrayList<EducationDTO>();
		edlist = educationsDTOS.getEducationsDTOS();
		List<ExperienceDTO> exlist = new ArrayList<ExperienceDTO>();
		exlist = experienceDTOS.getExperienceDTOS();
		List<FamilyDTO> falist = new ArrayList<FamilyDTO>();
		falist = familyDTOS.getFamilyDTOS();
		List<EmergencyContactDTO> emlist = new ArrayList<EmergencyContactDTO>();
		emlist = emergencyContactDTOS.getEmergencyContactDTOS();
		if (dto.getId() == null) {

			if (UserDTO.getType() == 1) {
				UserDTO userDTO = new UserDTO();
				userDTO.setUsername(dto.getIDCard());
				if (userService.findOne(userDTO) == null) {
					String newPwd = passwordEncoder.encodePassword("123456", userDTO.getUsername());
					userDTO.setPassword(newPwd);
					userDTO.setDeleted(false);
					userDTO.setType(UserType.Normal.getValue());
					Long id = userService.create(userDTO);
					UserDTO.setId(id);
					dto.setUser(UserDTO);
				} else {
					throw new BizException("此用户已存在");
				}
			} else {
				dto.setStatus(1);
			}
			Long id = employeeService.create(dto);
			dto.setId(id);
			List<EmployeeFileDTO> filist=employeeFileDTOS.getEmployeeFileDTOS();
			EmployeeDTO employee=new EmployeeDTO();
			employee.setId(id);
			employee=employeeService.findOne(employee);
		  if(filist!=null)
		  {
			  for (EmployeeFileDTO e:filist
					  ) {
				  if(e!=null&&!e.getFile().isEmpty())
				  {
					  file(request,e.getFiledescribe(),e.getFile(),employee);
				  }
			  }
		  }

			//学历添加
			for (EducationDTO e : edlist
					) {
				if (e.getMajor() == null && e.getMajor().equals("")) {
					e.setEmployee(dto);
					educationService.create(e);
				}
			}
			//工作经验添加


			for (ExperienceDTO e : exlist
					) {
				if (e.getPosition() != null && !e.getPosition().equals("")) {
					e.setEmployee(dto);
					experienceService.create(e);
				}

			}
			//家庭添加

			for (FamilyDTO e : falist
					) {
				if (e.getName() != null && !e.getName().equals("")) {
					e.setEmployee(dto);
					familyService.create(e);
				}
			}


			//紧急联系添加


			for (EmergencyContactDTO e : emlist
					) {
				if (e.getName() != null && !e.getName().equals("")) {
					e.setEmployee(dto);
					emergencyContactService.create(e);
				}
			}

		}
		if(UserDTO.getType()==1)
		{
			return ok();
		}else
		{
			return ok();
		}
	}
	@ResponseBody
	@RequestMapping(value = "/selectList")
	public void selectList(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("application/json;charset=UTF-8");
		List<DepartmentDTO> delist=departmentService.findAll();
	}

	//我的个人信息
	@RequestMapping(value = "/info")
	public String info(Map<String, Object> map, HttpServletRequest request) throws Exception {
		UserDTO userDTO = getCurrentUserDTO();
		List<DepartmentDTO> delist=departmentService.findAll();

		int type;
		EmployeeDTO dto = new EmployeeDTO();
		dto.setUser(userDTO);
		dto = employeeService.findOne(dto);
		if (dto == null) {
			map.put("show", "show");
			map.put("type", userDTO.getType());
			map.put("delist", delist);
			return "/admin/employee/employee_add_all";
		} else if (dto.getId() != null) {
			//部门
			DepartmentDTO departmentDTO=new DepartmentDTO();
			departmentDTO.setId(dto.getDepartment().getId());
			departmentDTO	=departmentService.findOne(departmentDTO);
			dto.setDepartment(departmentDTO);
			//学历
			EducationDTO education = new EducationDTO();
			education.setEmployee(dto);
			List<EducationDTO> edlist = educationService.findAll(education);
			//紧急联系人
			EmergencyContactDTO emergencyContact = new EmergencyContactDTO();
			emergencyContact.setEmployee(dto);
			List<EmergencyContactDTO> emlist = emergencyContactService.findAll(emergencyContact);
			//家庭
			FamilyDTO familyDTO = new FamilyDTO();
			familyDTO.setEmployee(dto);
			List<FamilyDTO> falist = familyService.findAll(familyDTO);
			//工作
			ExperienceDTO experienceDTO = new ExperienceDTO();
			experienceDTO.setEmployee(dto);
			List<ExperienceDTO> exlist = experienceService.findAll(experienceDTO);
			//附件，图片
			EmployeeFileDTO employeeFileDTO=new EmployeeFileDTO();
			employeeFileDTO.setEmployee(dto);
			List<EmployeeFileDTO> filist=employeeFileService.findAll(employeeFileDTO);
			map.put("filist", filist);
			map.put("type", userDTO.getType());
			map.put("edlist", edlist);
			map.put("emlist", emlist);
			map.put("falist", falist);
			map.put("exlist", exlist);
			map.put("n", dto);
			return "admin/employee/employee_detail";
		}
		return info(map,request);
	}

	private String Ext_Name = "gif,jpg,jpeg,png,bmp,swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2";

	public void file(HttpServletRequest request,
					 String filedescribe, MultipartFile file,
					 EmployeeDTO employee) throws Exception {
		Long id=employee.getUser().getId();
		if (!file.isEmpty()) {
			//上传文件名
			String filename = file.getOriginalFilename();
			// 得到上传文件的扩展名
			String fileExt = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
			// 检查扩展名
			// 如果需要限制上传的文件类型，那么可以通过文件的扩展名来判断上传的文件类型是否合法
			System.out.println("上传的文件的扩展名是：" + fileExt);
			if (!Ext_Name.contains(fileExt)) {
				throw new BizException("附件1文件类型不合法！");
			}
//			//文件名改为以描述名命名
//			filename = filedescribe1+"."+fileExt;
			//上传文件路径
			String path = request.getServletContext().getRealPath("/WEB-INF/employee_content/");
			path = path + "\\content" + id;
			File filepath = new File(path, filename);
			//判断路径是否存在，如果不存在就创建一个
			if (!filepath.getParentFile().exists()) {
				filepath.getParentFile().mkdirs();
			}
			EmployeeFileDTO employeeFileDTO=new EmployeeFileDTO();
			employeeFileDTO.setFiledescribe(filedescribe);
			employeeFileDTO.setSavepath(path+"\\"+filename);
			employeeFileDTO.setType(1);
			employeeFileDTO.setEmployee(employee);
			employeeFileDTO.setFilename(filename);
			//将上传文件保存到一个目标文件当中
			file.transferTo(new File(path + File.separator + filename));
			Long fileid=employeeFileService.create(employeeFileDTO);
		}
	}
	//文件下载
	@RequestMapping(value="/download")
	public ResponseEntity<byte[]> download(HttpServletRequest request,
										   @RequestParam("filename") String filename,  @RequestParam("id")Long id)throws Exception {
//		UserDTO userDTO=getCurrentUserDTO();
//		Long id=userDTO.getId();
		//下载文件路径
		String path = request.getServletContext().getRealPath("/WEB-INF/employee_content/");
		path=path+"\\"+"content"+id;
		File file = new File(path + File.separator + filename);
		HttpHeaders headers = new HttpHeaders();
		//下载显示的文件名，解决中文名称乱码问题
		String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
		//通知浏览器以attachment（下载方式）打开图片
		headers.setContentDispositionFormData("attachment", downloadFielName);
		//application/octet-stream ： 二进制流数据（最常见的文件下载）。
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
				headers, HttpStatus.CREATED);
	}

	//文件管理
	@RequestMapping(value = "/file")
	public String file(Map<String ,Object> map)
	{



			UserDTO userDTO=getCurrentUserDTO();
			EmployeeDTO e=new EmployeeDTO();
			e.setUser(userDTO);
			e=employeeService.findOne(e);
			//附件，图片
			EmployeeFileDTO employeeFileDTO=new EmployeeFileDTO();
			employeeFileDTO.setEmployee(e);
			List<EmployeeFileDTO> filist=employeeFileService.findAll(employeeFileDTO);
			map.put("filist", filist);
			map.put("n",e);

		return "admin/employee/employee_file";
	}

	//文件管理
	@RequestMapping(value = "/sc")
	public String sc(Map<String ,Object> map, EmployeeFileDTOS employeeFileDTOS,@RequestParam("id") long id,HttpServletRequest request) throws  Exception{
		UserDTO userDTO=getCurrentUserDTO();
		EmployeeDTO e=new EmployeeDTO();
		e.setUser(userDTO);
		e=employeeService.findOne(e);
		//附件，图片
		EmployeeFileDTO employeeFileDTO=new EmployeeFileDTO();
		employeeFileDTO.setEmployee(e);
		List<EmployeeFileDTO> filist=employeeFileService.findAll(employeeFileDTO);
		if(filist.size()>2)
		{
			return failPage("上传失败，最多上传三份文件！！");
		}

		List<EmployeeFileDTO> filist1 = employeeFileDTOS.getEmployeeFileDTOS();
		if (employeeFileDTOS != null) {
			for (EmployeeFileDTO em : filist1
					) {
				if (em != null && !em.getFile().isEmpty()) {
						file(request,em.getFiledescribe(),em.getFile(),e);
				}
			}
		}
		return successPage(null);
	}

}






